package learning.spring.contacts.web.restful.controllers;

import learning.spring.contacts.domain.Contact;
import learning.spring.contacts.service.ContactService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: bibro
 * Date: 22.02.14
 * Time: 14:35
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/contacts")
public class ContactRestController {
    final Logger logger = LoggerFactory.getLogger(ContactRestController.class);

    @Autowired
    private ContactService contactService;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public List<Contact> list() {
        List<Contact> contacts = (List<Contact>) contactService.findAll();
        return contacts;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Contact show(@PathVariable Long id) {
        logger.info("REST - Getting single contact element with id - [ " + id + " ]");
        Contact contact = contactService.findById(id);
        return contact;
    }

    @RequestMapping(value = "/filter")
    @ResponseBody
    public List<Contact> getByFirstName(@RequestParam(required = false) String firstName, @RequestParam(required = false) String lastName) {
        logger.info("REST - Getting contacts with firstname - [ " + firstName + " ] and lastname - [ " + lastName + " ]");
        List<Contact> contacts = (List<Contact>) contactService.findByFistNameAndLastName(firstName, lastName);
        return contacts;

    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Contact create(@RequestBody Contact contact) {
        logger.info("REST - creating new contact - [ " +contact + " ]");
        contactService.save(contact);
        logger.info("REST - contact created successfully");
        return contact;
    }

    @RequestMapping(value="/update/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public Contact update(@RequestBody Contact contact, @PathVariable Long id) {
        logger.info("Rest update");
//        contact.setId(id);
        contactService.update(contact);
        return contact;
    }


}
